package com.wtwd.campus.h5_manager.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wtwd.campus.h5_manager.common.Constant;
import com.wtwd.campus.h5_manager.common.PageDataVO;
import com.wtwd.campus.h5_manager.common.RespCode;
import com.wtwd.campus.h5_manager.common.RespEntity;
import com.wtwd.campus.h5_manager.entity.H5Customer;
import com.wtwd.campus.h5_manager.entity.H5ManageUser;
import com.wtwd.campus.h5_manager.entity.vo.H5CustomerVo;
import com.wtwd.campus.h5_manager.service.H5AuthService;
import com.wtwd.campus.h5_manager.service.H5CustomerService;
import com.wtwd.campus.h5_manager.service.H5ManagerUserService;
import com.wtwd.campus.utils.AppKeySecretUtils;
import io.swagger.annotations.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 * 1.只有总部账号可以创建客户
 * 2.但是客户可以创建自己的角色，给自己的的角色附加已有权限
 * 3.客户可创建账号，创建账号时,默认创建在自己的客户下(管理员可以选择客户创建,选择客户后)
 * 4.客户只能针对于自己的客户下的角色选择创建账号(管理员可根据选择的客户,选择客户下的角色进行创建)
 *
 * @author mjy
 * @since 2022-03-07
 */
@Api(tags = "h5平台客户管理")
@RestController
@RequestMapping("/webH5-manage-customer")
public class H5CustomerController {

    private static final Logger logger = LoggerFactory.getLogger(H5CustomerController.class);


    @Autowired
    private H5CustomerService customerService;

    @Autowired
    private H5ManagerUserService managerUserService;

    @Autowired
    private H5AuthService authService;

    @Autowired
    private H5ManagerUserService userService;


    /**
     * 只有总部人员可以对客户进行操作
     *
     * @param currentPage
     * @param pageSize
     * @param name(全模糊查询为空时查询所有)
     * @param request
     * @return
     */
    @ApiOperation(value = "查询H5客户分页数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "currentPage", value = "页数", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "pageSize", value = "页大小", required = true, dataTypeClass = Integer.class)
            , @ApiImplicitParam(name = "name", value = "客户名称", dataType = "String")
    })
    @ApiResponses({@ApiResponse(code = 602, message = "无权操作")
    })
    @GetMapping("/queryCustomerByConditions")
    public RespEntity<PageDataVO<H5CustomerVo>> queryCustomerByConditions(@RequestParam(defaultValue = "1") Integer currentPage,
                                                                          @RequestParam(defaultValue = "10") Integer pageSize,
                                                                          @RequestParam(value = "name", required = false) String name, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("queryCustomerByConditions currentPage={},pageSize={},name={} userId={}", currentPage, pageSize, name, userId);
      /*  Boolean aBoolean = authService.authUserIsHq(userId);
        if (!aBoolean) {
            return new RespEntity<>(RespCode.NO_PERMISSION);
        }*/
        H5ManageUser user = userService.getUserById(userId);
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("customerName", name);
        searchMap.put("customerId",user.getCustomerId());
        Page<H5CustomerVo> page = new Page<>(currentPage, pageSize);
        IPage<H5CustomerVo> customers = customerService.queryCustomerPage(searchMap, page);
        return RespEntity.success(customers);
    }


    /**
     * 创建客户，客户名称唯一
     *
     * @param customerVo
     * @param request
     * @return
     */
    @ApiOperation(value = "添加客户")
    @ApiResponses({@ApiResponse(code = 602, message = "无权操作"),
            @ApiResponse(code = 2002, message = "客户已经存在"),
            @ApiResponse(code = 604, message = "参数不能为空"),
    })
    @PostMapping("/addCustomer")
    public RespEntity addCustomer(@RequestBody H5CustomerVo customerVo, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("addCustomer userId={},customerVo={}", userId, customerVo.toString());
        if (StringUtils.isBlank(customerVo.getCustomerName())) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        Boolean aBoolean = authService.authUserIsHq(userId);
        if (!aBoolean) {
            return new RespEntity<>(RespCode.NO_PERMISSION);
        }
        Boolean authCustomerName = customerService.authCustomerName(customerVo);
        if (!authCustomerName) {
            return new RespEntity(RespCode.CUSTOMER_EXIST);
        }
        customerVo.setCreateTime(new Date().getTime());
        H5Customer customer = h5CustomerVoToH5Customer(customerVo);
        Integer rest = customerService.addCustomer(customer);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 修改客户名称
     *
     * @param customerVo
     * @param request
     * @return
     */
    @ApiOperation(value = "修改客户")
    @ApiResponses({@ApiResponse(code = 602, message = "无权操作"),
            @ApiResponse(code = 2002, message = "客户已经存在"),
            @ApiResponse(code = 604, message = "参数不能为空"),
    })
    @PutMapping("/updateCustomer")
    public RespEntity updateCustomer(@RequestBody H5CustomerVo customerVo, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("updateCustomer userId={},customerVo={}", userId, customerVo.toString());
        Boolean aBoolean = authService.authUserIsHq(userId);
        if (!aBoolean) {
            return new RespEntity<>(RespCode.NO_PERMISSION);
        }
        if (StringUtils.isBlank(customerVo.getCustomerName()) || customerVo.getId() == null) {
            return new RespEntity(RespCode.NO_PARAM);
        }
        Boolean authCustomerName = customerService.authCustomerName(customerVo);
        if (!authCustomerName) {
            return new RespEntity(RespCode.CUSTOMER_EXIST);
        }
        H5Customer customer = h5CustomerVoToH5Customer(customerVo);
        Integer rest = customerService.updateCustomerById(customer);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 删除客户时删除，客户拥有的角色,以及该客户下所有的账号
     * 同时删除，菜单权限表中记录
     *
     * @param customerId
     * @param request
     * @return
     */
    @ApiOperation("删除客户信息")
    @ApiImplicitParam(name = "customerId", value = "客户id", required = true, dataTypeClass = Integer.class, paramType = "path")
    @ApiResponses({
            @ApiResponse(code = 602, message = "无权操作"),
    })
    @DeleteMapping("/deleteCustomer/{customerId}")
    public RespEntity deleteCustomer(@PathVariable("customerId") Integer customerId, HttpServletRequest request) {
        String token = request.getHeader(Constant.H5_MANAGE_TOKEN_KEY);
        Integer userId = managerUserService.getUserIdByToken(token);
        if (userId == null) {
            return new RespEntity<>(RespCode.TOKEN_UNAUTHORIZED);
        }
        logger.info("deleteCustomer userId={},param={}", userId, customerId);
        Boolean aBoolean = authService.authUserIsHq(userId);
        if (!aBoolean) {
            return new RespEntity<>(RespCode.NO_PERMISSION);
        }
        Integer rest = customerService.deleteById(customerId);
        return new RespEntity(rest > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    private H5Customer h5CustomerVoToH5Customer(H5CustomerVo customerVo) {
        H5Customer customer = new H5Customer();
        customer.setId(customerVo.getId());
        customer.setCustomerName(customerVo.getCustomerName());
        String appKey = AppKeySecretUtils.getAppKey();
        customer.setAppKey(appKey);
        customer.setCreateTime(customerVo.getCreateTime());
        customer.setExpireTime(customerVo.getExpireTime());
        return customer;
    }



}

